<?php
/**
 * Created by PhpStorm.
 * User: yxb
 * Date: 2017/1/6
 * Time: 14:12
 */
namespace app\index\controller;

use think\Config;
use think\Db;
use think\Controller;
use think\Url;
use think\Loader;

class Pay extends Controller
{


    /**
     * 支付宝回调
     */
    public function alipay_notify($out_trade_no ='', $trade_no = '', $trade_status = '')
    {
        //$result = file_get_contents('php://input', 'r');
        //$result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
      //  Db::name('log')->insert(['name'=>$result['trade_status']]);
        if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
            Db::name("log")->insert(['name'=>"dddd"]);
//            $param = [
//                'order_id' => $result['out_trade_no'],
//                'out_trade_no' => $result['trade_no'],
//                'type' => 0,
//                'trading_type' => 0
//            ];
            $this->back_handle($out_trade_no, $trade_no,'',0,1);
        }
    }
    /**
    支付宝回调num
     */
    public function  alipay_notify_num($out_trade_no ='', $trade_no = '', $trade_status = ''){
       // $result = file_get_contents('php://input', 'r');
        //$result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
        Db::name('log')->insert(['name'=>$trade_status]);
        if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
          //  Db::name("log")->insert(['name'=>"sasad"]);
//            $param = [
//                'order_num' => $result['out_trade_no'],
//                'out_trade_no' => $result['trade_no'],
//                'type' => 1,
//                'trading_type' => 0
//            ];
            $this->back_handle('',$trade_no,$out_trade_no,1,1);
        }
    }


    /**
     *@param order_id
     *@param uid
     *@param assess_token
     */
    public function wx_pay($order_id = 0,$uid = '', $assess_token = '',$pswd='')
    {
        if (is_token($uid, $assess_token) == 0) {
            return format_return(0, '', "验证错误，请重新登录", 1);
        } else {
            empty($order_id) && $this->error("非法参数");
            $join = [
                ['goods g', 'g.id=o.g_id', 'left']
            ];
            $field = [
                'o.order_id',
                'o.price',
                'o.order_num',
                'g.subject',
                'o.integral',
                'g.status',
                'o.nums',
                'g.num'
            ];
            vendor('wechatpay.lib.WxPayApi');
            $member = Db::name("members")->where('uid',$uid)->find();
            $order = Db::name("orders")->alias("o")->where("order_id", $order_id)->join($join)->field($field)->find();
            if($order['status'] == 0){
                return format_return(0,'','支付失败，商品已下架');
            }
            if($order['num'] < $order['nums']){
                return format_return(0,'','库存不足');
            }
            if($pswd){
                $payment = Db::name("pay")->where('uid',$uid)->field('payment')->find();
                if($payment['payment']!=md5($pswd)){
                    return format_return(0, '', "支付密码错误");
                }
            }
            if($member['integral'] < $order['integral'] || $member['status_type'] == 0){
                return format_return(0, '', "积分不够，支付失败");
            }
            if($member['balance'] > $order['price']){
                //余额大于商品价格
                $member['balance'] = $member['balance'] - $order['price'];
                $member['integral'] = $member['integral'] - $order['integral'];
                $data = [
                    'balance'=>$member['balance'],
                    'integral' => $member['integral']
                ];
                Db::name("members")->where('uid',$uid)->update($data);
                $this->back_handle($order_id,'','',0,2,1);
                return format_return(0, "1", "余额付款成功");
            }else{
                $total=bcsub($order['price'],$member['balance'],1)*100;
               
                vendor('wechatpay.lib.WxPayApi');
               
               // $total = $order['price'] - $member['balance'];
                $time = time();
                $input = new \WxPayUnifiedOrder();
                $input->SetBody($order['subject']);
                $input->SetOut_trade_no($order_id);
                $input->SetTotal_fee($total);
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", $time + 1800));
                $input->SetTrade_type("APP");
                $input->SetNotify_url("www.tianjunhai.com/index/pay/wechat_notify_id");
                $order_param = \WxPayApi::unifiedOrder($input);
                return format_return(1, $order_param, "参数获取成功");
            }

        }
    }
    //微信支付统一下单order_num
    /**
     *@param order_num
     *@param uid
     *@param assess_token
     */
    public function wx_pay_num($order_num = '',$uid = '', $assess_token = '',$pswd='')
    {
        if (is_token($uid, $assess_token) == 0) {
            return format_return(0, '', "验证错误，请重新登录", 1);
        } else {
            empty($order_num) && $this->error("非法参数");
            $join = [
                ['goods g', 'g.id=o.g_id', 'left']
            ];
            $field = [
                'o.order_id',
                'o.price',
                'o.order_num',
                'g.subject',
                'g.status',
                'o.integral'
            ];
            vendor('wechatpay.lib.WxPayApi');
            $member = Db::name("members")->where('uid',$uid)->find();
            $orders = Db::name("orders")->alias("o")->where("order_num", $order_num)->join($join)->field($field)->select();
            $subject = '';
            foreach($orders as $key => $value){
                $subject .= $value['subject'];
                if($value['status'] == 0){
                    return format_return(0,'','支付失败，商品已下架');
                }
            }
            
            if($pswd){
                $payment = Db::name("pay")->where('uid',$uid)->field('payment')->find();
                if($payment['payment']!=md5($pswd)){
                    return format_return(0, '', "支付密码错误");
                }
            }
          
            $integral = array_sum(array_column($orders,'integral'));
            $price = array_sum(array_column($orders,'price'));
            if($member['integral'] < $integral || $member['status_type'] == 0){
                return format_return(0, '', "积分不够，支付失败");
            }
            
            if($member['balance'] > $price){
                //余额大于商品价格
                $member['balance'] = $member['balance'] - $price;
                $member['integral'] = $member['integral'] - $integral;
                $data = [
                    'balance'=>$member['balance'],
                    'integral' => $member['integral']
                ];
                Db::name("members")->where('uid',$uid)->update($data);
                Db::name("log")->insert(['name'=>"wxpay_num".$order_num]);
                $this->back_handle('','',$order_num,1,2,1);
                return format_return(0, "1", "余额付款成功");
            }else{
                vendor('wechatpay.lib.WxPayApi');
                // $total = $order['price'] - $member['balance'];
               
                
                
               // $total = $price - $member['balance'];
               $total=bcsub($price,$member['balance'],2)*100;
                
                $time = time();
                $input = new \WxPayUnifiedOrder();
                $input->SetBody($subject);
                $input->SetOut_trade_no($order_num);
                $input->SetTotal_fee($total);
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", $time + 1800));
                $input->SetTrade_type("APP");
                $input->SetNotify_url("www.tianjunhai.com/index/pay/wechat_notify_num");
                $order_param = \WxPayApi::unifiedOrder($input);
                return format_return(1, $order_param, "参数获取成功");
            }

        }
    }
    //支付回调order_id
    public function wechat_notify_id()
    {
        //Db::name("log")->insert(['name'=>"sss"]);
        Loader::import('wechatpay.lib.WxPayConfig', VENDOR_PATH, EXT);
        $result = file_get_contents('php://input', 'r');
        $result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
        if ($result['result_code'] === 'SUCCESS' && $result['mch_id'] === \WxPayConfig::MCHID && $result['appid'] === \WxPayConfig::APPID) {
//            $param = [
//                'order_id' => $result['out_trade_no'],
//                'out_trade_no' => $result['transaction_id'],
//                'type' => 0,
//                'trading_type' => 0
//            ];
            $this->back_handle($result['out_trade_no'],$result['transaction_id'],'',0,0);
        }
    }
    //支付回调order_id
    public function wechat_notify_num()
    {
        Loader::import('wechatpay.lib.WxPayConfig', VENDOR_PATH, EXT);
        $result = file_get_contents('php://input', 'r');
        $result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
        if ($result['result_code'] === 'SUCCESS' && $result['mch_id'] === \WxPayConfig::MCHID && $result['appid'] === \WxPayConfig::APPID) {
           // Db::name("log")->insert(['name'=>"微信回调"]);
//            $param = [
//                'order_num' => $result['out_trade_no'],
//                'out_trade_no' => $result['transaction_id'],
//                'type' => 1,
//                'trading_type' => 0
//            ];
            $this->back_handle('',$result['transaction_id'],$result['out_trade_no'],1,0);
        }
    }

    /**
     * 回调
     * @param order_id 订单id
     * @param order_num 订单num
     * @param type 0 id 1 num 2 balance
     * @param out_trade_no 交易号
     * @param trading_type 0 wx 1 alipay
     */
    public function back_handle($order_id = '', $out_trade_no = '', $order_num = '', $type = 0, $trading_type = 0,$is_balance = 0)
    {
        //order_id
        if ($type == 0) {
            $where = [
                'order_id' => $order_id,
                'status' => 0,
                'is_cancel' => 0,
            ];
            $orders = Db::name('orders')->where($where)->find();
            $member = Db::name("members")->where("uid",$orders['uid'])->find();
            Db::name("log")->insert(['name'=> "order_id"]);
            if (!empty($orders)) {
                if($is_balance == 0){
                    $integral = $member['integral'] - $orders['integral'];
                    $update = [
                        'balance' => 0,
                        'integral' => $integral
                    ];
                    Db::name("members")->where("uid",$orders['uid'])->update($update);
                }

                $data = [
                    'status' => 1,
                    'trade_no' => $out_trade_no,
                    'trading_type' => $trading_type
                ];
                Db::name('orders')->where($where)->update($data);
                $goods = Db::name("goods")->where('id', $orders['g_id'])->find();
                $update_goods = [
                    'num' => $goods['num']-$orders['nums'],
                    'sell_num' => $goods['sell_num']+$orders['nums']
                ];
                Db::name("goods")->where('id', $orders['g_id'])->update($update_goods);
            }
        } else if ($type == 1){
            Db::name("log")->insert(['name'=>"order_num"]);

            //order_num
            $where = [
                'order_num' => $order_num,
                'status' => 0,
                'is_cancel' => 0,
            ];
            $orders = Db::name('orders')->where($where)->select();
            $member = Db::name("members")->where("uid",$orders[0]['uid'])->find();
            if (!empty($orders)) {
                if($is_balance == 0){
                    $integral = $member['integral'] - array_sum(array_column($orders,"integral"));
                    $update = [
                        'balance' => 0,
                        'integral' => $integral
                    ];
            Db::name("members")->where("uid",$member['uid'])->update($update);
                }
                $data = [
                    'status' => 1,
                    'trade_no' => $out_trade_no,
                    'trading_type' => $trading_type
                ];
                Db::name('orders')->where($where)->update($data);
                $g_ids = array_column($orders,'g_id');
                $where_g = [
                    'g.is_delete' => 0,
                    'g.id' => array('in',$g_ids)
                ];
                 $join = [
                ['goods g', 'g.id=o.g_id', 'left']
                 ];
                 
                $field = [
                 'g.*',  
                'o.nums'
                
                ];
                $goods = Db::name("orders")->alias("o")->where($where_g)->join($join)->field($field)->select();
              
                foreach($goods as $key => $value){
                     $num=$value['num']-$value['nums'];
                     $sell_num=$value['sell_num']+$value['nums'];
                     $updata = [
                        'num' => $num,
                        'sell_num' => $sell_num
                    ];
                    Db::name("goods")->where('id',$goods[$key]['id'])->update($updata);
                    unset($updata);
                }
            }
        }
    }
    /**
    扫码支付
     * @param uid
     * @param assess_token
     * @param type 交易类型
     * @param total 金额
     * @param s_id 门店id
     * @param remarks 备注
     * @param trading_type 交易方式 0 wx 1 alipay
     */
    public function scan($uid = '',$assess_token = '',$type = 0,$total = '',$s_id = '',$remarks = '',$trading_type = 0,$pswd=''){

        if (is_token($uid, $assess_token) == 0) {
            return format_return(0, '', "验证错误，请重新登录", 1);
        } else {
            $where = [
                'status' => 1,
                'id' => $s_id
            ];
            $store = Db::name("store_unline")->where($where)->find();
            $member = Db::name("members")->where("uid",$uid)->find();
            if(empty($member['store_id'])){
                Db::name("members")->where("uid",$uid)->update(['store_id'=>$s_id]);
            }else{
                if($member['store_id'] != $s_id){
                    return format_return(0,'',"该门店与绑定的门店不一样，不能在此消费!");
                }
                
                if($pswd){
                    $payment = Db::name("pay")->where('uid',$uid)->field('payment')->find();
                    if($payment['payment']!=md5($pswd)){
                        return format_return(0, '', "支付密码错误");
                    }
                }
                $data = [
                    's_id' => $s_id,
                    's_name' => $store['name'],
                    'type' => $type,
                    'price' => $total,
                    'uid' => $uid,
                    'trading_type' => $trading_type,
                    'integral' => $total,
                    'remarks' => $remarks
                ];
                $order_id = Db::name("records")->insertGetId($data);
                if($trading_type == 0){
                    //微信
                    if($member['balance'] >= $total){
                        //余额大于商品价格
                        $order = Db::name("records")->where('id',$order_id)->find();
                        if(empty($order['out_trade_no'])){
                            //余额大于商品价格
                            $member['balance'] = $member['balance'] - $total;
                            $member['integral'] = $member['integral'] + $total;
                            Db::name("log")->insert(['name'=>"余额支付".$member['balance']]);
                            $data = [
                                'balance' => $member['balance'],
                                'integral' => $member['integral']
                            ];
                            Db::name("members")->where('uid',$uid)->update($data);
                            $where = [
                                'type' => 2,
                                's_id' => $s_id
                            ];
                            $recive_member = Db::name("members")->where($where)->find();
                            $_total_now = $total+$recive_member['balance'];
                            $data = [
                                'balance' => $_total_now
                            ];
                            Db::name("log")->insert(['name'=>"余额支付".($total+$recive_member['balance'])]);
                            $updates = [
                                'out_trade_no'=>$order_id,
                                'trading_type' => 2
                            ];
                            Db::name("records")->where('id',$order_id)->update($updates);
                            Db::name("members")->where($where)->update($data);
                            return format_return(0,'3','余额支付成功');
                        }else{
                            return format_return(0,'3','余额支付成功');
                        }
                    }else{
                        vendor('wechatpay.lib.WxPayApi');
                        $total = $total - $member['balance'];
                        $time = time();
                        $input = new \WxPayUnifiedOrder();
                        $input->SetBody("线下门店支付");
                        $input->SetOut_trade_no($order_id);
                        $input->SetTotal_fee($total*100);
                        $input->SetTime_start(date("YmdHis"));
                        $input->SetTime_expire(date("YmdHis", $time + 1800));
                        $input->SetTrade_type("APP");
                        $input->SetNotify_url("www.tianjunhai.com/index/pay/scan_wx_notify");
                        $order_param = \WxPayApi::unifiedOrder($input);
                        return format_return(1, $order_param, "参数获取成功");
                    }
                }else{
                    //支付宝
                    if($member['balance'] >=$total){
                        $order = Db::name("records")->where('id',$order_id)->find();
                        if(empty($order['out_trade_no'])){
                            //余额大于商品价格
                            $member['balance'] = $member['balance'] - $total;
                            $member['integral'] = $member['integral'] + $total;
                            Db::name("log")->insert(['name'=>"余额支付".$member['balance']]);
                            $data = [
                                'balance' => $member['balance'],
                                'integral' => $member['integral']
                            ];
                            Db::name("members")->where('uid',$uid)->update($data);
                            $where = [
                                'type' => 2,
                                's_id' => $s_id
                            ];
                            $recive_member = Db::name("members")->where($where)->find();
                            $_total_now = $total+$recive_member['balance'];
                            $data = [
                                'balance' => $_total_now
                            ];
                            Db::name("log")->insert(['name'=>"余额支付".($total+$recive_member['balance'])]);
                            $updates = [
                                'out_trade_no'=>$order_id,
                                'trading_type' => 2
                            ];
                            Db::name("records")->where('id',$order_id)->update($updates);
                            Db::name("members")->where($where)->update($data);
                            return format_return(0,'3','余额支付成功');
                        }else{
                            return format_return(0,'3','余额支付成功');
                        }
                        //$this->back_handle($order_id,'','',0,2);
                    }else {
                        $total = $total - $member['balance'];
                        // 异步通知地址
                        $notify_url = urlencode('http://www.tianjunhai.com/index/pay/scan_alipay_notify');
                        // 订单标题
                        $subject = "线下门店支付";
                        // 订单详情
                        $body = "线下门店支付";
                        // 订单号，示例代码使用时间值作为唯一的订单ID号
                        $out_trade_no = $order_id;
                        // 支付宝合作者身份ID，以2088开头的16位纯数字
                        $partner = "2088021878456483";
                        // 支付宝账号
                        $seller_id = '370562505@qq.com';
                        // 商品网址
                        $base_path = urlencode('http://www.tianjunhai.com');
                        $parameter = array(
                            'service' => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
                            'partner' => $partner,                   // 必填，合作商户号
                            '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
                            'out_trade_no' => $out_trade_no,              // 必填，商户网站唯一订单号
                            'subject' => $subject,                   // 必填，商品名称
                            'payment_type' => '1',                        // 必填，支付类型
                            'seller_id' => $seller_id,                 // 必填，卖家支付宝账号
                            'total_fee' => $total,                     // 必填，总金额，取值范围为[0.01,100000000.00]
                            'body' => $body,                      // 必填，商品详情
                            'it_b_pay' => '1d',                       // 可选，未付款交易的超时时间
                            'notify_url' => $notify_url,                // 可选，服务器异步通知页面路径
                            'show_url' => $base_path,                  // 可选，商品展示网站
                            'sign_type' => 'RSA'
                        );
                        //生成需要签名的订单
                        $orderInfo = $this->createLinkstring($parameter);
                        //print_r($orderInfo);die;
                        //签名
                        $sign = $this->rsaSign($orderInfo);
                        //生成订单
                        $order_param = $orderInfo.'&sign="'.$sign.'"&sign_type="RSA"';
                        return format_return(1,$order_param,"数据获取成功");
                    }
                }
            }
        }
    }

    public function back_handle_records($id = '',$status = 0,$type = 0){
        $data = [
            'status' => $status,
            'trading_type' => $type
        ];
        Db::name("records")->where('id',$id)->update($data);
    }
    /**
    扫码支付回调支付宝
     */
    public function scan_alipay_notify($out_trade_no ='', $trade_no = '', $trade_status = ''){
        if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
            $order = Db::name("records")->where('id',$out_trade_no)->find();
            if(empty($order['out_trade_no'])){
                $param = [
                    'out_trade_no' => $trade_no,
                    'type' => 0,
                    'trading_type' => 1,
                    'status' => 1
                ];
                Db::name("records")->where('id',$out_trade_no)->update($param);
                $record = Db::name("records")->where('id',$out_trade_no)->find();
                //门店账户余额修改
                Db::name("log")->insert(['name'=>"门店id".$record['s_id']]);
                $where = [
                    'type' => 2,
                    's_id' => $record['s_id']
                ];
                $recive_member = Db::name("members")->where($where)->find();
                $_total =$recive_member['balance'] + $record['price'];
                $data = [
                    'balance' => $_total
                ];
                Db::name("members")->where($where)->update($data);
                //用户账户余额积分修改
                $member = Db::name("members")->where('uid',$record['uid'])->find();
//            $balance = $member['balance'] - $record['price'];
//            if($balance < 0){
//                $balance = 0;
//            }
                $integral = $member['integral'] + $record['price'];
                unset($data);
                $data = [
                    'balance' => 0,
                    'integral' => $integral
                ];
                Db::name("members")->where("uid",$record['uid'])->update($data);
            }

        }
    }

    /**
    扫码支付微信回调
     *
     */
    public function scan_wx_notify(){
        Loader::import('wechatpay.lib.WxPayConfig', VENDOR_PATH, EXT);
        $result = file_get_contents('php://input', 'r');
        $result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
        if ($result['result_code'] === 'SUCCESS' && $result['mch_id'] === \WxPayConfig::MCHID && $result['appid'] === \WxPayConfig::APPID) {
            $order = Db::name("records")->where('id',$result['out_trade_no'])->find();
            if(empty($order['out_trade_no'])){
                $param = [
                    'out_trade_no' => $result['transaction_id'],
                    'type' => 0,
                    'trading_type' => 0,
                    'status' => 1
                ];
                Db::name("records")->where('id',$result['out_trade_no'])->update($param);
                $record = Db::name("records")->where('id',$result['out_trade_no'])->find();
                //门店账户余额修改
                $where = [
                    'type' => 2,
                    's_id' => $record['s_id']
                ];
                $recive_member = Db::name("members")->where($where)->find();
                $_total =$recive_member['balance'] + $record['price'];
                $data = [
                    'balance' => $_total
                ];
                Db::name("members")->where($where)->update($data);
                //用户账户余额积分修改
                $member = Db::name("members")->where('uid',$record['uid'])->find();
//                $balance = $member['balance'] - $record['price'];
//                if($balance < 0){
//                    $balance = 0;
//                }
                $integral = $member['integral'] + $record['price'];
                unset($data);
                $data = [
                    'balance' => 0,
                    'integral' => $integral
                ];
                Db::name("members")->where("uid",$record['uid'])->update($data);

            }

        }
    }
    // 对签名字符串转义
    private function createLinkstring($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
            $arg.=$key.'="'.$val.'"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);
        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
        return $arg;
    }
// 签名生成订单信息
    private function rsaSign($data) {
        $priKey = "-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDg5NZ42g9QvqIV03LJZUFm4MLTADV1VrsJx2nSRskVcBud1XHv
sBWWnAD8779PDxJaCzZtQn0AtEKGy8demmczRZrn7mu6yv3WHfsfg5xVOzk+mWDD
N6+fDD+BrfxT1QO6hq/FaBy8p/G6TmGY8RriZgdEPVHCjyfernJ/ZExEJwIDAQAB
AoGAKu6knteJ+vEZgi8mh5nj3V7k8mDk06yl8hz2b6UBuCz5qKzZnlcwF9taOO8P
x2jqKPRhBISf1mWTGaaHPeEd+AkZ/SH4YZ+596dMw+pYF9GTH4CQ8QuFZymr+3ZO
jMjXsjMjdGYM7RNhQunqU0Ak4bGMC0F4cQQ64gBhqJrypbkCQQD2USUIXaR/KXin
4CB5TOKDFLigGjlcqW9DzZ8VIBFQi+AW8luDmaxeLz+y97zx2NrSIPF0uB7Ki9R3
Zs4J+WZVAkEA6bwZIFc6AAvz2f4JwpdEMg5xeigUG5fSNXFkLU/ZByDuCt6NE7DQ
ZkbcrYR6HicgGlciZqJjMllpMbZI4cbkiwJBAMkUkzPSJmC8/UemuzvrHRs/Rj1F
S0Cu/SsP6Gd5h0kG90gkT7sOL92vmsPCZJfWnURfKl5LlK9rGWbkIR2ZYQUCQQDQ
0rTAKC4xjHw47rZZnDvZXP4VXWlZnbK4/K27rfMAY3NJUrxIM1h9iCHxBML13Y7Y
+bBKchqeCTPqrik/TisxAkBFfuP37iYtC13lWBcCMmI2hB15wEyW6EtZagjLUSo6
jo/97UB+lVSHI/mpYrFu0qtBk1waxF6jRZ1XgxRKoZ0M
-----END RSA PRIVATE KEY-----";
//        $priKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALOAicUPRZ0Hru8w43A7DIEZjVSrqTrRJoaYojr5hXgdsEobqeFCL31alKqz8KMtS9gxO2gkZtBsj1GsajYFiIrz3FUAeOSh6xxPOZCS82aqIxGmeBUUUcHtgvS2dyIva1Zt9S6vdBF4TNWFE2m9tvrqfENsUjoN6HdBdPIkD8+3AgMBAAECgYAsxreXLIQU88GzcOKLMG+iFJmosVl5joqpsJFnXK7qk51SHyx1QGlQP7QuEMzKJ5Zvy3giNlJfU3U8zmGAMEkq1ONS08/JVmLMndLxiRaWfnES76eUz01Y6ZxZC4YpaWsxzDleVrh2h57rRb63qiRhXLdNi5GrJw0DMQKgN/YCYQJBAOpI4Lhjjv59+xbehxya5MMUgstbZf2YQZwVf90V7P46QqVxKsLd09mHyoliCSM6IlhB89r406TU6vl/y006dYsCQQDEI8aZ2N8IBSq7NmdrEau6dzQ1NUsS7r1n9RaE1NJ7WF0ECNRhfMpNkZJ1PcnyThA9J8wb6n0i+3XDMzTUWwwFAkAzy8Lq4Q/nEcEmUDI8z73Np0Y3YVCOHVA8CsDHBybrGcRMQVW72UER8aSEdQkiIaMgMgyQl7xqz6vXVzqCK297AkBLQ18mEe4jabgn9oxgrXs0JiHGeRjBvxK3HXjyp6fM5O9saOb2Mah/c2i7zGX9sK7SiL7tx2EVV2Cs8q1G/1jxAkEAsQCC62m1yS0ije/gBwfOx7M9U3J8a1vpxPzH408TprtOz4xxGAjZU7D05v6FQUi/g5Z7LhFQaiVfuQXyPDpGDg==";
//        $priKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
//            wordwrap($priKey, 64, "\n", true) .
//            "\n-----END RSA PRIVATE KEY-----";
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }
    /**
    测试支付
     * @param uid
     * @param assess_token
     * @param order_id
     * @param order_num
     * @param type 0订单id 1订单num
     */
    public function order_pay($uid = '',$assess_token= '',$order_id = '', $order_num = '',$type = ''){
            //订单id
            if($type == 0){
                $order = Db::name("orders")->where("order_id",$order_id)->find();
                $data = [
                    'status' => 1,
                    'pay_timestamp' => time()
                ];
                if($order['status'] == 0){
                    Db::name("orders")->where("order_id",$order_id)->update($data);
                    $member = Db::name("members")->where('uid',$uid)->find();
                    //修改门店分润金额
                    $where = [
                        'id' => $member['store_id'],
                        'status' => 1
                    ];
                    $store_un = Db::name("store_unline")->where($where)->find();
                    $member_st = Db::name("members")->where('uid',$store_un['uid'])->find();
                    $member_st['balance'] = $member_st['balance'] + $order['price']*$store_un['profit'];
                    Db::name("members")->where('uid',$member_st['uid'])->update(['balance' => $member_st['balance'] ]);
                    //修改供货商金额
                    $line = Db::name("store_online")->where('id',$order['s_id'])->find();
                    $member_lin = Db::name("members")->where("uid",$line['uid'])->find();
                    $member_lin['balance'] = $member_lin['balance'] + 0.4*$order['price'];
                    Db::name("members")->where('uid',$line['uid'])->update(['balance' => $member_lin['balance']]);
                    return format_return(1,'','支付成功');
                }
            }else{
                //order_num
                $orders = Db::name("orders")->where("order_num",$order_num)->find();
                $data = [
                    'status' => 1,
                    'pay_timestamp' => time()
                ];
                Db::name("orders")->where("order_num",$order_num)->update($data);
                $member = Db::name("members")->where('uid',$uid)->find();
                //修改门店分润金额
                $where = [
                    'id' => $member['store_id'],
                    'status' => 1
                ];
                $store_un = Db::name("store_unline")->where($where)->find();
                $member_st = Db::name("members")->where('uid',$store_un['uid'])->find();
                foreach($orders as $key => $value){
                    $member_st['balance'] = $member_st['balance'] + $value['price']*$store_un['profit'];
                }
                Db::name("members")->where('uid',$member_st['uid'])->update(['balance' => $member_st['balance'] ]);
                //修改供货商金额
                foreach($orders as $key => $value){
                    $line = Db::name("store_online")->where('id',$value['s_id'])->find();
                    $member_lin = Db::name("members")->where("uid",$line['uid'])->find();
                    $member_lin['balance'] = $member_lin['balance'] + 0.4*$value['price'];
                    Db::name("members")->where('uid',$line['uid'])->update(['balance' => $member_lin['balance']]);
                    unset($line);
                    unset($member_lin);
                }
                return format_return(1,'','支付成功');
            }
        }

    /**
    会员支付
     * @param uid
     * @param assess_token
     * @param p_id
     * @param trading_type 0 wx 1 alipay
     */
    public function member_pay($uid = '',$assess_token = '',$p_id = '',$trading_type = 0,$s_id =''){
      
        Db::name('members')->where(array('uid'=>$uid))->update(['store_id'=>$s_id]);
//        dump(123);die;
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else {
            //生成订单
            $price = Db::name("member_price")->where('id',$p_id)->find();
            $order_id = str_pad(str_replace('.', '', microtime(true)), 14, 0);
            $data = [
                'order_id' => $order_id,
                'price' => $price['price'],
                'p_id' => $p_id,
                'status' => 0,
                'uid' => $uid
            ];
//            dump($data);
            Db::name("member_order")->insert($data);
           
            if($trading_type == 0){
              
//                dump($trading_type);
                //微信支付
                vendor('wechatpay.lib.WxPayApi');
                // $total = $order['price'] - $member['balance'];
                $time = time();
                $input = new \WxPayUnifiedOrder();
                $input->SetBody("会员门票");
                $input->SetOut_trade_no($order_id);
                //$price['price']*100;
                $input->SetTotal_fee(1);
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", $time + 1800));
                $input->SetTrade_type("APP");
                $input->SetNotify_url("www.tianjunhai.com/index/pay/notify_wx_member");
                $order_param = \WxPayApi::unifiedOrder($input);
                return format_return(1, $order_param, "参数获取成功");
            }else{
                //支付宝支付
                // 支付宝合作者身份ID，以2088开头的16位纯数字
                $partner = "2088021878456483";
                // 支付宝账号
                $seller_id = '370562505@qq.com';
                // 商品网址
                $base_path = urlencode('http://www.tianjunhai.com');
                // 异步通知地址
                $notify_url = urlencode('http://www.tianjunhai.com/index/pay/notify_alipay_member');
               // $total = $total - $member['balance'];
                $parameter = array(
                    'service'        => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
                    'partner'        => $partner,                   // 必填，合作商户号
                    '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
                    'out_trade_no'   => $order_id,              // 必填，商户网站唯一订单号
                    'subject'        => "会员门票",                   // 必填，商品名称
                    'payment_type'   => '1',                        // 必填，支付类型
                    'seller_id'      => $seller_id,                 // 必填，卖家支付宝账号
                    'total_fee'      => $price['price'],                     // 必填，总金额，取值范围为[0.01,100000000.00]
                    'body'           => "会员门票",                      // 必填，商品详情
                    'it_b_pay'       => '1d',                       // 可选，未付款交易的超时时间
                    'notify_url'     => $notify_url,                // 可选，服务器异步通知页面路径
                    'show_url'       => $base_path,                  // 可选，商品展示网站
                    'sign_type'      => 'RSA'
                );
                //生成需要签名的订单
                $orderInfo = $this->createLinkstring($parameter);
                //签名
                $sign = $this->rsaSign($orderInfo);
                //生成订单
                $order_param = $orderInfo.'&sign="'.$sign.'"&sign_type="RSA"';
                return format_return(1,$order_param,"数据获取成功");
            }
        }
    }

    /**
    会员微信支付回调
     */
    public function notify_wx_member(){
        Loader::import('wechatpay.lib.WxPayConfig', VENDOR_PATH, EXT);
        $result = file_get_contents('php://input', 'r');
        $result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
        if ($result['result_code'] === 'SUCCESS' && $result['mch_id'] === \WxPayConfig::MCHID && $result['appid'] === \WxPayConfig::APPID) {
            $order = Db::name("member_order")->where('order_id',$result['out_trade_no'])->find();
            if(empty($order['trade_no'])){
                $data = [
                    'trade_no' => $result['transaction_id'],
                    'status' => 1
                ] ;
                Db::name("member_order")->where('order_id',$result['out_trade_no'])->update($data);
                Db::name("member_order")->where('order_id',$result['out_trade_no'])->find();
                $member = Db::name("members")->where('uid',$order['uid'])->find();
                $member['integral'] = $member['integral'] + $order['price'];
                //门店获利50%
                $men = Db::name('store_unline')->where(array('id'=>$member['store_id']))->find();
                $m = Db::name("members")->where('uid',$men['uid'])->find();
                $yue['balance'] = $m['balance'] + $order['price']*0.5;
                Db::name("members")->where('uid',$men['uid'])->update(['balance'=>$yue['balance']]);
                //修改成正式会员
                $update_member = [
                    'integral' => $member['integral'],
                    'status_type' => 1,
                ];
                Db::name("members")->where('uid',$order['uid'])->update($update_member);
            }

        }
    }
    /**
    会员支付宝回调
     */
    public function notify_alipay_member($out_trade_no ='', $trade_no = '', $trade_status = ''){
        if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
            $order = Db::name("member_order")->where('order_id',$out_trade_no)->find();
            if(empty($order['trade_no'])){
                $data = [
                    'trade_no' => $trade_no,
                    'status' => 1
                ] ;
                Db::name("member_order")->where('order_id',$out_trade_no)->update($data);

                $member = Db::name("members")->where('uid',$order['uid'])->find();
                //门店获利50%
                $men = Db::name('store_unline')->where(array('id'=>$member['store_id']))->find();
                $m = Db::name("members")->where('uid',$men['uid'])->find();
                $yue['balance'] = $m['balance'] + $order['price']*0.5;
                Db::name("members")->where('uid',$men['uid'])->update(['balance'=>$yue['balance']]);
                //
                $member['integral'] = $member['integral'] + $order['price'];
                //修改成正式会员
                $update_member = [
                    'integral' => $member['integral'],
                    'status_type' => 1,
                ];
                Db::name("members")->where('uid',$order['uid'])->update($update_member);
            }

        }
    }
    /**
    获取会员价格
     * @param uid
     * @param assess_token
     */
    public function get_memberprice($uid = '', $assess_token = ''){
        if(is_token($uid,$assess_token) == 0){
            return format_return(0,'',"验证错误，请重新登录",1);
        }else {
            $price = Db::name("member_price")->select();
            if(!empty($price)){
                return format_return(1,$price,'数据获取成功');
            }else{
                return format_return(0,'','数据获取失败');
            }
        }
    }

    /**
    门店申请支付回调微信
     */
    public function unline_wx_notify(){
        Loader::import('wechatpay.lib.WxPayConfig', VENDOR_PATH, EXT);
        $result = file_get_contents('php://input', 'r');
        $result = (array)simplexml_load_string($result, null, LIBXML_NOCDATA);
        if ($result['result_code'] === 'SUCCESS' && $result['mch_id'] === \WxPayConfig::MCHID && $result['appid'] === \WxPayConfig::APPID) {
            $data = [
                'trad_out' => $result['transaction_id'],
                'is_pay' => 1,
                'pay_type' => 0
            ] ;
            Db::name("store_unline")->where('order_id',$result['out_trade_no'])->update($data);
        }
    }
    /**
     * 门店申请支付回调支付宝
     */
    public function unline_alipay_notify($out_trade_no ='', $trade_no = '', $trade_status = ''){
        if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
            $data = [
                'trad_out' => $trade_no,
                'is_pay' => 1,
                'pay_type' => 0
            ];
            Db::name("store_unline")->where('order_id',$out_trade_no)->update($data);
        }
    }
}
